<?php

class Dispatcher_Exception extends Exception
{ }

class Dispatcher
{
    var $error_404_controller;
    var $error_404_action;
    var $error_500_controller;
    var $error_500_action;
    
    public function Dispatcher () {
        $this->error_404_controller = "error";
        $this->error_404_action = "err404";
        $this->error_500_controller = "error";
        $this->error_500_action = "err500";
    }
    
    public function getControllerClassName ($controller) {
        //return ucwords(strtolower($controller)) . "Controller";
        return $controller . "Controller";
    }
    public function getControllerFileName ($controller) {
        return "controller/" . $controller . "_controller.php";
    }
    
    public function dispatch (Request $request, Response $response) {
        $controller = $request->controller;
        $action = $request->action;
        if (!$controller || !$action) {
            $controller = $this->error_404_controller;
            $action = $this->error_404_action;
            $response->appendException(new Dispatcher_Exception("No such controller."));
        }
        
        $controller_filename = $this->getControllerFileName($controller);
        $controller_classname = $this->getControllerClassName($controller);
        require_once $controller_filename;
        $c_obj = new $controller_classname();
        $c_obj->setResponse($response);
        $c_obj->setRequest($request);
        $c_obj->init();
        $c_obj->$action($request->params);
        
    }
}

